"""峰谷时间调度（主模型调用时间窗口）"""
"""高峰期调度器（根据时间段调整资源）"""
import datetime
import threading
import time
from typing import Dict, List, Tuple
from fin_senti_entity_platform.utils.config_loader import ConfigLoader
from fin_senti_entity_platform.utils.logger import Logger


class PeakScheduler:
    """高峰期调度器类，用于根据时间段调整服务资源分配"""
    
    def __init__(self):
        """初始化高峰期调度器"""
        self.logger = Logger().get_logger(__name__)
        self.config = ConfigLoader().get_config('service', 'cost_optimization')
        self.enabled = self.config.get('enabled', False)
        self.peak_hours = self._parse_peak_hours(self.config.get('peak_hours', []))
        self.current_mode = 'normal'  # 'normal' 或 'peak'
        self.callbacks = []
        self._running = False
        self._thread = None
        
    def _parse_peak_hours(self, peak_hours_config: List[Dict[str, str]]) -> List[Tuple[datetime.time, datetime.time]]:
        """解析高峰期配置"""
        peak_hours = []
        for period in peak_hours_config:
            try:
                start_time = datetime.datetime.strptime(period['start'], '%H:%M').time()
                end_time = datetime.datetime.strptime(period['end'], '%H:%M').time()
                peak_hours.append((start_time, end_time))
            except Exception as e:
                self.logger.error(f"解析高峰期配置失败: {str(e)}")
        return peak_hours
    
    def is_peak_hour(self) -> bool:
        """检查当前是否为高峰期"""
        if not self.enabled or not self.peak_hours:
            return False
        
        current_time = datetime.datetime.now().time()
        for start_time, end_time in self.peak_hours:
            if start_time <= current_time <= end_time:
                return True
        return False
    
    def register_callback(self, callback):
        """注册模式切换回调函数"""
        if callback not in self.callbacks:
            self.callbacks.append(callback)
    
    def _notify_callbacks(self, mode: str):
        """通知所有回调函数模式切换"""
        for callback in self.callbacks:
            try:
                callback(mode)
            except Exception as e:
                self.logger.error(f"执行回调函数失败: {str(e)}")
    
    def start(self):
        """启动高峰期检测线程"""
        if self.enabled and not self._running:
            self._running = True
            self._thread = threading.Thread(target=self._run, daemon=True)
            self._thread.start()
            self.logger.info("高峰期调度器已启动")
    
    def stop(self):
        """停止高峰期检测线程"""
        if self._running:
            self._running = False
            if self._thread:
                self._thread.join(timeout=2.0)
            self.logger.info("高峰期调度器已停止")
    
    def _run(self):
        """运行高峰期检测"""
        while self._running:
            # 检查是否需要切换模式
            should_be_peak = self.is_peak_hour()
            if should_be_peak and self.current_mode == 'normal':
                self.current_mode = 'peak'
                self.logger.info("进入高峰期模式")
                self._notify_callbacks('peak')
            elif not should_be_peak and self.current_mode == 'peak':
                self.current_mode = 'normal'
                self.logger.info("进入正常模式")
                self._notify_callbacks('normal')
            
            # 每分钟检查一次
            time.sleep(60)
    
    def get_current_mode(self) -> str:
        """获取当前模式"""
        return self.current_mode


# 创建全局实例
global_peak_scheduler = PeakScheduler()


def get_peak_scheduler() -> PeakScheduler:
    """获取高峰期调度器实例"""
    return global_peak_scheduler